import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Button, Table, message, DatePicker, Select, Modal } from 'antd'
import { UpOutlined, DownOutlined, DownloadOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import moment from 'moment'
import { addWindow } from '@redux/actions'
import style from '@pages/filingCaseManage/CaseManage.module.less'
import { getArbitratorListRequest, getEmployeeListRequest } from './ajax'
import { awaitWrap, decompressLicenseAndMobile } from '@js/tool'
import { json2Excel } from '@js/excel'
import SelectedModal from './components/SelectedModal/Index'
import StatusModal from './components/StatusModal/Index'
import Dictionary from '@js/dictionary'

const { Item } = Form
const { Option } = Select
const { confirm } = Modal

const layout = {
  labelCol: { flex: '100px' }
}

// 获取表格字段配置
function getColumns () {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      align: 'center',
      width: 60
    },
    {
      title: '月份',
      dataIndex: 'title',
      key: 'title'
    },
    {
      title: '仲裁员',
      dataIndex: 'name',
      key: 'name',
      sorter: true
    },
    {
      title: '收入',
      dataIndex: 'real_amount_sum',
      key: 'real_amount_sum'
    },
    {
      title: '扣税情况',
      dataIndex: 'tax_sum',
      key: 'tax_sum'
    },
    {
      title: '银行卡号',
      dataIndex: 'bank_accountno',
      key: 'bank_accountno'
    }
  ]
}

class SimpleSearch extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    arbitratorList: [],
    employeeList: [],
    condition: [],
    selectedRowKeys: [],
    selectedRows: [],
    statusList: [],
    visible: false,
    statusVisible: false,
    orderField: '',
    order: '',
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    }
  }

  formRef = React.createRef()

  getParams (form) {
    const { pagination, orderField, order } = this.state
    const { current, pageSize } = pagination
    form = form || this.formRef.current.getFieldsValue()
    const condition = []
    this.setState({ loading: true })
    if (form.arbitratorid) {
      condition.push({ k: 'arbitratorid', o: '=', v: form.arbitratorid })
    }
    if (form.beginTime) {
      const str = form.beginTime.format('YYYY-MM')
      condition.push({ k: 'period_time', o: '>=', v: Math.floor(moment(`${str}-01 00:00:00`).valueOf() / 1000) })
    }
    if (form.endTime) {
      const str = form.endTime.format('YYYY-MM')
      const d = moment(`${str}-01 23:59:59`)
      d.add(1, 'month')
      d.subtract(1, 'day')
      condition.push({ k: 'period_time', o: '<=', v: Math.floor(d.valueOf() / 1000) })
    }
    this.setState({
      condition
    })
    delete form.beginTime
    delete form.endTime
    const data = {
      current,
      page_size: pageSize,
      condition: JSON.stringify(condition)
    }
    if (orderField && order) {
      data.order = order === 'ascend' ? 'asc' : 'desc'
      data.order_field = orderField
    }
    return data
  }

  // 获取案件数据
  getTableData (form) {
    const { pagination } = this.state
    const { current, pageSize } = pagination
    const params = this.getParams(form)
    this.$get('/api/xapc/remuneration/aggrlist', params).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }, filters, sorter = { field: this.state.orderField, order: this.state.order }) {
    this.setState({
      orderField: sorter.field,
      order: sorter.order,
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.formRef.current.resetFields()
    this.setState({
      condition: [],
      selectedRowKeys: [],
      selectedRows: []
    })
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  initFormByMeta () {
    const c = this.formRef.current
    const { formData = {} } = this.props.meta || {}
    c.resetFields()
    c.setFieldsValue(formData)
    c.submit()
  }

  async initArbitratorList () {
    const [e, d] = await awaitWrap(getArbitratorListRequest())
    if (e === null && d !== null) {
      this.setState({ arbitratorList: d.list })
    }
  }

  async initEmpolyeeList () {
    const [e, d] = await awaitWrap(getEmployeeListRequest())
    if (e === null && d !== null) {
      this.setState({ employeeList: d })
    }
  }

  // 二次弹框确认下载excel
  confirmDownload () {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '您确定要导出excel吗？',
      onOk: () => {
        this.downloadExcel()
      }
    })
  }

  // 获取当前查询条件的全部数据，并下载excel
  downloadExcel () {
    const current = 1
    const pageSize = 1000000
    const hide = message.loading('导出中', 300)
    const { orderField, order } = this.state
    const params = {
      current,
      page_size: pageSize,
      condition: JSON.stringify(this.state.condition)
    }
    if (orderField && order) {
      params.order = order === 'ascend' ? 'asc' : 'desc'
      params.order_field = orderField
    }
    this.$get('/api/xapc/remuneration/aggrlist', params).then(res => {
      hide()
      if (res.status === 1) {
        const list = res.data.list.map((l, i) => {
          decompressLicenseAndMobile(l)
          return {
            序号: pageSize * (current - 1) + i + 1,
            '*姓名': l.name,
            '*证件类型': '居民身份证',
            '*证件号码': l.license,
            '*所得项目': '一般劳务报酬所得',
            '*收入': l.real_amount_sum,
            免税收入: '',
            商业健康保险: '',
            税延养老保险: '',
            其他: '',
            允许扣除的税费: '',
            减免税额: '',
            备注: '',
            开户行: l.bank,
            银行卡号: l.bank_accountno,
            扣税情况: l.tax_sum,
            月份: l.title
          }
        })
        list.push({
          '办案报酬（实发）': this.state.realAmountSum,
          代缴税费: this.state.taxSum,
          实发金额: this.state.realAmountWithouttaxSum
        })
        json2Excel([{ data: list, sheetname: '仲裁员酬金' }], '仲裁员酬金')
      } else {
        return message.warning(res.message)
      }
    }).catch(() => hide())
  }

  changeProcesserid (v) {
    const list = this.state.employeeList
    for (let i = 0; i < list.length; i++) {
      if (list[i].name === v) {
        this.formRef.current.setFieldsValue({ processerid: list[i].id })
        break
      }
    }
  }

  changeArbitrator (v) {
    const list = this.state.arbitratorList
    for (let i = 0; i < list.length; i++) {
      if (list[i].name === v) {
        this.formRef.current.setFieldsValue({ arbitratorid: list[i].id })
        break
      }
    }
  }

  componentDidUpdate (prev) {
    if (prev.meta !== this.props.meta) {
      this.initFormByMeta()
    }
  }

  componentDidMount () {
    this.initFormByMeta()
    this.initEmpolyeeList()
    this.initArbitratorList()
    const d = new Dictionary()
    d.init('仲裁员酬金状态')
      .then(res => {
        this.setState({
          statusList: d.getList('仲裁员酬金状态')
        })
      })
      .catch(e => {
        console.error(e)
      })
  }

  // 渲染搜索表单的展开和收起
  renderToggleBtns () {
    if (this.state.searchToggleBtn) {
      return (
        <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
          <span>展开</span>
          <UpOutlined />
        </Button>
      )
    }
    return (
      <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
        <span>收起</span>
        <DownOutlined />
      </Button>
    )
  }

  render () {
    const columns = getColumns.call(this)
    return (
      <div className={style.container}>
        <SelectedModal visible={this.state.visible} data={this.state.selectedRows} hide={() => this.setState({ visible: false })} onChange={(l) => this.setState({ selectedRowKeys: l.map(l => l.id), selectedRows: l })} />
        <StatusModal visible={this.state.statusVisible} hide={() => this.setState({ statusVisible: false })} data={this.state.selectedRowKeys} refreshData={() => { this.tableChange(this.state.pagination); this.setState({ selectedRowKeys: [], selectedRows: [] }) }} statusList={this.state.statusList} />
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form
              name='doc_seal_list' {...layout} ref={this.formRef} onFinish={v => {
                this.setState({
                  selectedRowKeys: [],
                  selectedRows: []
                })
                this.getTableData(v)
              }}
            >
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='起始月份' name='beginTime'>
                    <DatePicker className={style.full} picker='month' format='YYYY-MM' placeholder='请选择日期' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='结束月份' name='endTime'>
                    <DatePicker className={style.full} picker='month' format='YYYY-MM' placeholder='请选择日期' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item name='arbitratorid' noStyle><span /></Item>
                  <Item label='仲裁员姓名' name='arbitrator'>
                    <Select placeholder='请选择' allowClear showSearch onChange={(v) => this.changeArbitrator(v)}>
                      {this.state.arbitratorList.map((li, i) => {
                        return (
                          <Option key={i} value={li.name}>{li.name}</Option>
                        )
                      })}
                    </Select>
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={24}>
                  <Item>
                    <div className={style['search-btns']}>
                      <Button type='primary' ghost htmlType='submit'>搜索</Button>
                      <Button htmlType='reset' onClick={() => this.resetHandle()}>重置
                      </Button>
                      {/* {this.renderToggleBtns()} */}
                    </div>
                  </Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['download-btn-line']} style={{ marginBottom: '12px' }}>
          <Button type='primary' ghost onClick={() => this.confirmDownload()} icon={<DownloadOutlined />}>导出excel</Button>
        </div>
        <div className={style['table-container']}>
          <Table
            loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={(...args) => this.tableChange(...args)}
          />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(SimpleSearch)
